package com.csx.micrometer.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.PriorityOrdered;

import java.util.HashMap;
import java.util.Map;

/**
 * @author cuisongxu
 * @date 2022/11/20 19:46
 */
public class SpringContextUtil implements ApplicationContextAware, PriorityOrdered {

    private static Logger logger = LoggerFactory.getLogger(SpringContextUtil.class);

    private static ApplicationContext applicationContext;

    public SpringContextUtil() {

    }

    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }

    public static boolean containsBean(String beanName) {
        return applicationContext.containsBean(beanName);
    }

    public static <T> T getBean(Class<T> beanClass) {
        return applicationContext.getBean(beanClass);
    }

    public static <T> T getBean(String name, Class<T> beanClass) {
        return applicationContext.getBean(name, beanClass);
    }

    public static <T> Map<String, T> getBeansOfType(Class<T> type) {
        try {
            return applicationContext.getBeansOfType(type);
        } catch (Exception e) {
            return new HashMap<>();
        }
    }

    public static <T> T getBeanIfPresent(Class<T> type) {
        try {
            T t = applicationContext.getBean(type);
            return t;
        } catch (Exception e) {
            //APM 工具类，获取不到bean，返回null
			logger.error("get Bean Excption",e);
            return null;
        }
    }

    public static <T> T getBeanIfPresent(String beanName, Class<T> type) {
        try {
            T t = applicationContext.getBean(beanName, type);
            return t;
        } catch (Exception e) {
            return null;
        }
    }


    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public static void setApplicationContextByInitializer(ApplicationContext applicationContext) {
        SpringContextUtil.applicationContext = applicationContext;
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }
}
